package com.dt.app.websocket;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author DT
 * @date 2021/11/15 12:31
 */
@Component
@ServerEndpoint("/api/ws/{userId}")
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 存放WebSocketServer对象。
     */
    public static final ConcurrentHashMap<String,WebSocketServer> USER_MAP_SOCKET;
    static {
        USER_MAP_SOCKET = new ConcurrentHashMap<>();
    }

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 用户ID
     */
    private String currentUserId = "";

    /**
     * 连接建立成功调用的方法
     * @param session 会话session
     * @param userId 用户名
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        currentUserId = userId;
        this.session = session;
        USER_MAP_SOCKET.put(userId, this);
        log.info("->>>用户连接:"+userId+",当前在线人数为:" + USER_MAP_SOCKET.size());
        try {
            sendMessage();
        } catch (IOException e) {
            log.error("websocket连接异常...");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        USER_MAP_SOCKET.remove(currentUserId);
        log.info("->>>用户离开:"+currentUserId+",当前在线人数为:" + USER_MAP_SOCKET.size());
    }

    /**
     * 发生错误时调用的方法
     */
    @OnError
    public void onError(Session session, Throwable e) {
        log.error("->>>用户调用错误:"+currentUserId+",错误原因:" + e.getMessage());
    }

    public synchronized void sendMessage() throws IOException {
        for (String key : USER_MAP_SOCKET.keySet()) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("count",USER_MAP_SOCKET.size());
                USER_MAP_SOCKET.get(key).sendMessageAllUser(String.valueOf(jsonObject));
            } catch (IOException e) {
                log.error("->>>发送消息错误:"+currentUserId+",错误原因:" + e.getMessage());
            }
        }
    }

    /**
     * 群发消息
     * @param message 消息内容
     * @throws IOException
     */
    public void sendMessageAllUser(String message) throws IOException {
        synchronized(this) {
            try {
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("->>>发送消息错误:"+currentUserId+",错误原因:" + e.getMessage());
            }
        }
    }

    /**
     * 重写hashcode方法
     */
    @Override
    public int hashCode() {
        return UUID.randomUUID().hashCode();
    }
}
